public class OpportunityExtensionVF {

    private final Opportunity[] opportunity = new Opportunity[1];
    private ID oppId = null;
    
    private	ID planId = null;
    private	Double planQuota = 0;
    private Double planOTE = 0;
    private String payoutType = '';
    
    public List<Opportunity> opportunityList {get; set;}
	public Rate__c[] currentRateList {get; set;}     
    public String expectedCredit {get; set;}   
    public String ytdAttainment {get; set;}    
    public String commissionRate {get; set;}    
    public String commissionAmount {get; set;} 
    public Boolean claimedAmountFlag {get; set;}
    public Boolean claimedRateFlag {get; set;}
    public Boolean fileClaimButtonFlag {get; set;}
    public Boolean estimateButtonFlag {get; set;}
    public Boolean ytdAttainmentFlag {get; set;}
    public String comments {get; set;}  
    public String claimStatus {get; set;}  

    private Claim__c existingClaim = new Claim__c();
    public OpportunityExtensionVF(ApexPages.StandardController myController)
    {
        opportunity[0] = (Opportunity)myController.getRecord();
        oppId = opportunity[0].id;//[select Opportunity__c from Claim__c where id = : opportunity[0].id].Opportunity__c;
        //oppId = ApexPages.currentPage().getParameters().get('id');
        opportunityList = [select Name, Amount, AccountId, Opportunity.Account.Name, ExpectedRevenue, Type, Description, OwnerId, Opportunity.Owner.Name, CloseDate, LeadSource, Opportunity.Campaign.Name, MainCompetitors__c, OrderNumber__c, CurrentGenerators__c, TrackingNumber__c from Opportunity where id = :oppId];
        ytdAttainment = String.valueOf(0.0);
        ytdAttainmentFlag = claimedRateFlag = claimedAmountFlag = fileClaimButtonFlag = true;
        claimObj();
    }

    
    public List<Opportunity> getOpportunityDetails()
    {
        return opportunityList;
    }
    
    public PageReference estimate()
    {
        if(commissionRate != null)
            commissionAmount = String.valueOf((Double.valueOf(commissionRate) * Double.valueOf(expectedCredit)) / 100);
        if(commissionAmount != null)
        {
        	estimateButtonFlag = true;
        	fileClaimButtonFlag = !fileClaimButtonFlag;
        }
        return null;
    }

    public PageReference lookupPlanDocument()
    {
        return null;
    }

    public PageReference fileClaim()
    {
    	try
    	{
	        Claim__c claim = new Claim__c(Plan__c = planId, Participant__c = UserInfo.getUserId(), Payout_Type__c = payoutType, Attainment__c = Double.valueOf(ytdAttainment), Commission_Rate__c = Double.valueOF(commissionRate), Commission_Amount__c = Double.valueOf(commissionAmount), Credit__c = Double.valueOf(expectedCredit), Opportunity__c = opportunity[0].id, Comments__c = comments, Claim_Status__c = 'Pending Approval', Filing_Date__c = Date.today());
	        insert claim;
	        fileClaimButtonFlag = !fileClaimButtonFlag;
	        Approval.ProcessSubmitRequest request =new Approval.ProcessSubmitRequest();
	        request.setObjectId(claim.Id);
	        Approval.ProcessResult result = Approval.process(request);
    	}
    	catch(Exception e)
    	{
        	ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
    	}        
        return null;
    }

    private void claimObj()
    {
    	//Check if Plan is assigned to the Participant.
    	Plan_Assignable__c[] planAssignableList = [select Id, Plan_Role__c, Plan_Assignable__c.Plan_Role__r.Plan__c, Plan_Assignable__c.Plan_Role__r.Plan__r.Quota__c, Plan_Assignable__c.Plan_Role__r.Plan__r.OTE__c from Plan_Assignable__c p where p.Effective_Start_Date__c <= :opportunityList[0].CloseDate and p.Effective_End_Date__c >= :opportunityList[0].CloseDate order by createddate desc limit 1];
        Double ytdAtt = 0;
    	
    	try
    	{
        	if(planAssignableList.size() > 0)
        	{
        		//Get the Plan and check if it Close Date falls in b/w Plan Period
	        	planId = planAssignableList[0].Plan_Role__r.Plan__c;
	        	planQuota = planAssignableList[0].Plan_Role__r.Plan__r.Quota__c;
	        	planOTE = planAssignableList[0].Plan_Role__r.Plan__r.OTE__c;
        	}
	        Plan_Participant__c[] pList = [select YTD_Attainment__c from Plan_Participant__c where Plan__c = :planId and Participant__c = :UserInfo.getUserId()];
	        for(Plan_Participant__c p :pList)
	        {
	        	ytdAtt += p.YTD_Attainment__c;
	        }
    	}
    	catch(Exception e)
    	{
        	ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
    	}

        Claim__c[] claimObj = [select  id, Claim__c.Opportunity__r.Amount, Commission_Amount__c, Commission_Rate__c, Attainment__c, Credit__c, Comments__c, Claim_Status__c from Claim__c where Opportunity__c = :oppId];
        if(claimObj.size() > 0)
        {
            expectedCredit = String.valueOf(claimObj[0].Opportunity__r.Amount);
        	ytdAttainment = String.valueOf(ytdAtt);
            commissionRate = String.valueOf(claimObj[0].Commission_Rate__c);
            commissionAmount = String.valueOf(claimObj[0].Commission_Amount__c);
            claimStatus = claimObj[0].Claim_Status__c;
            if(claimStatus == 'Pending Approval' || claimStatus == 'Approved')
            	fileClaimButtonFlag = estimateButtonFlag = true;
        }
        else
        {
        	try
        	{
	        	if(planAssignableList.size() > 0)
	        	{
		        	//Work on this later to find the claims made till now on a particular Plan
		        	Claim__c[] claimsList = [select Credit__c from Claim__c where Plan__c = :planId and Claim_Status__c = 'Approved'];
		        	
		        	currentRateList = [select Rate_Type__c, Min_Attainment__c, Max_Attainment__c, Min_Credit__c, Max_Credit__c, Rate__c from Rate__c where Plan__c = :planId order by createddate];
		        	if(currentRateList.size() > 0)
		        		payoutType = currentRateList[0].Rate_Type__c;
		        	if(opportunityList[0].Amount <= planQuota)
		        	{
		                expectedCredit = String.valueOf(opportunityList[0].Amount);
			        	ytdAttainment = String.valueOf(ytdAtt);
		                if(currentRateList[0].Rate_Type__c == 'Attainment')
		                {
		                	if(currentRateList[0].Min_Attainment__c < 100)
			                	commissionRate = String.valueOf(currentRateList[0].Rate__c);
		                }
		                claimStatus = 'Draft';
		        	}
	        		
	        	}
        	}
        	catch(Exception e)
        	{
	        	ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        	}
        	
        	/*Plan__c[] plansList = [select id from Plan__c where Start_Date__c <= :opportunityList[0].CloseDate and End_Date__c >= :opportunityList[0].CloseDate];
            if(plansList.size() > 0)
            {
                Rate__c[] ratesList = [select Rate__c from  Rate__c where Plan__c = :plansList[0].id];
//                Plan_Role__c pRolesList = [select Id from Plan_Role__c where ]
                
                expectedCredit = opportunityList[0].Amount;
                commissionRate = ratesList[0].Rate__c;
                claimStatus = 'Draft';
                
            }*/
        }
    }
    
    public Claim__c getClaimData()
    {
        if(existingClaim != null)
            return existingClaim;
    //    else
      //      return toBeDeletedClaim;        
        return null;
    }

}